#include "Avalon/CodecsTests/ReverseDecoder.hpp"
#include "Avalon/IO/Buffer.hpp"

using namespace Avalon;
using namespace Avalon::Codecs;
using namespace Avalon::Codecs::Tests;
using namespace Avalon::IO;
using namespace std;

ReverseDecoder::ReverseDecoder() {}

ReverseDecoder::~ReverseDecoder() {}

bool ReverseDecoder::IsDecodeInPlaceSupported() const {
  return true;
}

void ReverseDecoder::Decode(const void* source, int sourceSize,
    void* destination, int destinationSize, Out<int> encodedSize) {
  int length = min(sourceSize, destinationSize);
  const char* sourceIterator = static_cast<const char*>(source) + length - 1;
  char* destinationIterator = static_cast<char*>(destination);
  while(true) {
    *destinationIterator = *sourceIterator;
    ++destinationIterator;
    if(sourceIterator == source) {
      break;
    }
    --sourceIterator;
  }
  *encodedSize = length;
}

void ReverseDecoder::Decode(const void* source, int sourceSize,
    Buffer* destination, Out<int> encodedSize) {
  int startingPoint = destination->GetSize();
  destination->Grow(sourceSize);
  Decode(source, sourceSize, destination->GetMutableData() + startingPoint,
    sourceSize, Store(encodedSize));
}
